﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TrabalhoAnaliseAlgoritmo.Metodos
{
    public static class KMP
    {
        public static Int32 DoKMP(String text, String pattern)
        {
            int textLength = text.Length;
            int patternLength = pattern.Length;
            var fail = Prefix(pattern);
            int i = 0, j = 0;

            while (i < textLength)
            {
                if (pattern[j].Equals(text[i]))
                {
                    if (j == patternLength - 1)
                    {
                        return i - patternLength + 1;
                    }
                    i++;
                    j++;
                }
                else if (j > 0)
                {
                    j = fail[j - 1];
                }
                else
                {
                    i++;
                }
            }
            return -1;
        }

        private static Int32[] Prefix(String pattern)
        {
            var length = pattern.Length;
            var lengthFail = new Int32[pattern.Length];
            lengthFail[0] = 0;
            int i = 1, j = 0;

            while (i < length)
            {
                if (pattern[j].Equals(pattern[i]))
                {
                    lengthFail[i] = j + 1;
                    i++;
                    j++;
                }
                else if (j > 0)
                {
                    j = lengthFail[j - 1];
                }
                else
                {
                    lengthFail[i] = 0;
                    i++;
                }
            }
            return lengthFail;
        }
    }
}
